package com.study.zouchao.superproject.homepage.presenter;

import android.content.Context;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.common.base.Throwables;
import com.google.gson.Gson;
import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.cache.NewsListCacheUtil;
import com.study.zouchao.superproject.homepage.adapter.MyExpandableListViewAdapter;
import com.study.zouchao.superproject.homepage.adapter.NetworkImageHolderView;
import com.study.zouchao.superproject.homepage.adapter.NewsListAdapter;
import com.study.zouchao.superproject.homepage.contract.IHomePageContract;
import com.study.zouchao.superproject.homepage.model.entity.DataBean;
import com.study.zouchao.superproject.homepage.model.impl.AdBaiduConnModel;
import com.study.zouchao.superproject.homepage.model.impl.AdCacheModel;
import com.study.zouchao.superproject.homepage.model.impl.AdConnModel;
import com.study.zouchao.superproject.homepage.model.impl.BaiduNewsModel;
import com.study.zouchao.superproject.homepage.model.impl.CourseDataCacheModel;
import com.study.zouchao.superproject.homepage.model.impl.CourseDataConnModel;
import com.study.zouchao.superproject.homepage.model.result.BannerItem;
import com.study.zouchao.superproject.homepage.model.result.entity.BaiduAdResult;
import com.study.zouchao.superproject.homepage.model.result.entity.BaiduNewResult;
import com.study.zouchao.superproject.test.entity.FileInfo;
import com.study.zouchao.superproject.travellist.adapter.TravelRecyclerViewAdapter;
import com.study.zouchao.superproject.travellist.entity.TravelListResult;
import com.study.zouchao.superproject.util.CharTools;
import com.study.zouchao.superproject.util.CharacterUtil;
import com.study.zouchao.superproject.util.LogLongUtil;
import com.study.zouchao.superproject.util.SetUtils;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import rx.functions.Action1;
import rx.internal.operators.BackpressureUtils;

import static com.study.zouchao.superproject.base_zou.cache.NewsListCacheUtil.getBaiduNewsCacheByList;
import static com.study.zouchao.superproject.travellist.model.TravelModel.URL;

/**
 * Created by Administrator on 2017/2/9.
 */

public class HomePagePresenter implements IHomePageContract.IHomePagePresenter {
    private static final String TAG = "DataP";
    private Context mContext;
    //V
    private IHomePageContract.IHomePageView mView;
    private List<BannerItem> mBannerItems;
    private ConvenientBanner mConvenientBanner;
    //ExpanableListView的adapter
    private MyExpandableListViewAdapter mExpanableLvAdapter;
    //ExpanableListView的map
    private LinkedHashMap<String, List<FileInfo>> mParentChildMap;
    private AdConnModel mAdConnModel;
    private AdCacheModel mAdCacheModel;
    private AdBaiduConnModel mAdBaiduConnModel;
    private CourseDataConnModel mCourseConnModel;
    private CourseDataCacheModel mCourseCacheModel;
    private BaiduNewsModel mBaiduModel;
    private boolean mIsRefreshingSchoolPics = false, mIsRefreshingCourseData = false;

    private List<BaiduNewResult.DataBean.ListBean> mData;
    private NewsListAdapter mAdapter;

    private int mStartIndex = 0, mEndIndex = 10, mTotalSize;

    private View mRv;
    private Handler mHandler = new Handler();

    public HomePagePresenter(Context context, IHomePageContract.IHomePageView view, MyExpandableListViewAdapter.IOnChildItemClickListener listener) {
        mContext = context;
        mView = view;
        mListener = listener;
        init();
    }

    private void init() {
        mBannerItems = new ArrayList<>();

        mConvenientBanner = mView.getConvenientBanner();

        mParentChildMap = new LinkedHashMap<>();

        mAdConnModel = new AdConnModel();
        mAdCacheModel = new AdCacheModel();
        mAdBaiduConnModel = new AdBaiduConnModel();
        mCourseConnModel = new CourseDataConnModel();
        mCourseCacheModel = new CourseDataCacheModel();
        mBaiduModel = new BaiduNewsModel();

        initView();
        loadData();
    }

    private void initView() {
        //广告栏
        mConvenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, mBannerItems).setPageIndicator(new int[]{R.drawable.circle_unfocused,
                R.drawable.circle_focused});
    }


    @Override
    public void loadData() {
        loadAllDataFromCache();
        onRefreshingData();
    }

    private MyExpandableListViewAdapter.IOnChildItemClickListener mListener;

    @Override
    public void setOnChildListener(MyExpandableListViewAdapter.IOnChildItemClickListener listener) {
        mListener = listener;
    }

    @Override
    public void loadSeeMore() {

    }

    @Override
    public void initRecyclerView(RecyclerView rv) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        rv.setLayoutManager(layoutManager);
        rv.setHasFixedSize(true);
        rv.setNestedScrollingEnabled(false);
        mData = new ArrayList<>();
        //为RecyclerView加Adapter
        mAdapter = new NewsListAdapter(mContext, mData);
        View footLoadingView = LayoutInflater.from(mContext).inflate(R.layout.footview_recyclerview, rv, false);
        mAdapter.setFooterView(footLoadingView);
//        mAdapter.setOnItemClickListener(this);
        mView.setSeeMoreLoading(footLoadingView);
        rv.setAdapter(mAdapter);
    }

    @Override
    public void onDestroyPresente() {

    }

    @Override
    public void showRefreshingLoading(boolean isShow) {

    }

    @Override
    public void showSeeMoreLoading(boolean isShow) {

    }

    @Override
    public void setSeeMoreLoading(View footerLoadingView) {

    }

    private void loadAllDataFromCache() {
        loadBaiduAdDataFromCache();
        loadCourseDataFromCache();
    }

    @Override
    public void onRefreshingData() {
        toggleShoolPicsRefreshing(true);
        toggleCourseDataRefreshing(true);
        mView.showRefreshingAnimation(true);
        connAdPic();
        connData();
    }

    private void attemptHideRefreshingAnimation() {
        Log.i("WoCaoWOLELEGE......re.." + mIsRefreshingSchoolPics, "co.." + mIsRefreshingCourseData);
        if (!mIsRefreshingSchoolPics && !mIsRefreshingCourseData)
            mView.showRefreshingAnimation(false);
    }


    private void toggleShoolPicsRefreshing(boolean isShow) {
        mIsRefreshingSchoolPics = isShow;
        attemptHideRefreshingAnimation();
    }

    private void toggleCourseDataRefreshing(final boolean isShow) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mIsRefreshingCourseData = isShow;
                attemptHideRefreshingAnimation();
            }
        });
    }

    @Override
    public void connAdPic() {
        mAdBaiduConnModel.connAd(new AdBaiduConnModel.IGetBaiduAdListener() {
            @Override
            public void onSuccess(BaiduAdResult result) {
                successGetBaiduAdPics(result);
                toggleShoolPicsRefreshing(false);
            }

            @Override
            public void onFailure(Throwable throwable, String msg) {
                toggleShoolPicsRefreshing(false);
            }
        });
    }

    private void successGetBaiduAdPics(BaiduAdResult result) {
        if (result==null || result.getData()==null
                || result.getData().getNews()==null
                || result.getData().getNews().size()==0)
                return;
        saveNewBaiduAdData2Cache(result.getData().getNews());
        loadBaiduAdDataFromCache();
    }

    private void saveNewBaiduAdData2Cache(List<BaiduAdResult.DataBean.NewsBean> newData) {
        mAdCacheModel.saveBaiduAd2SharePre(mContext, newData);
//        ToastUtils.showShort(mContext, "轮播图更新成功");
    }

    private void loadBaiduAdDataFromCache() {
        List<BaiduAdResult.DataBean.NewsBean> data = mAdCacheModel.listBaiduAdPics(mContext);
        if (data == null) return;
        showBaiduAd(data);
    }

    private void showBaiduAd(List<BaiduAdResult.DataBean.NewsBean> slideImgs) {
        List<BannerItem> items = new ArrayList<>();
        //生成所需的数据
        for (int i = 0; i < slideImgs.size(); i++) {
            List<BaiduAdResult.DataBean.NewsBean.ImageurlsBean> imgs = slideImgs.get(i).getImageurls();
            if (imgs!=null && imgs.size()>0) {
            Log.d("ad", imgs.get(0).getUrl());
                items.add(new BannerItem("第" + i + "张", imgs.get(0).getUrl()));
            }
        }
        //广告栏
        mConvenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, items).setPageIndicator(new int[]{R.drawable.circle_unfocused, R.drawable.circle_focused});
    }

    /*
     * 参考这个
     */
    private void successGetAdPics(List<String> newData) {
        saveNewData2Cache(newData);
        loadAdDataFromCache();
    }

    private void saveNewData2Cache(List<String> newData) {
        mAdCacheModel.save2SharePre(mContext, newData);
    }

    private void loadAdDataFromCache() {
        List<String> data = mAdCacheModel.listAdPics(mContext);
        if (data == null) return;
        showAd(data);
    }

    private void showAd(List<String> slideImgs) {
        List<BannerItem> items = new ArrayList<>();
        //生成所需的数据
        for (int i = 0; i < slideImgs.size(); i++) {
            items.add(new BannerItem("第" + i + "张", slideImgs.get(i)));
        }
        //广告栏
        mConvenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, items).setPageIndicator(new int[]{R.drawable.circle_unfocused, R.drawable.circle_focused});
    }

    /**
     * CourseData
     */
    @Override
    public void connData() {
        toggleCourseDataRefreshing(true);
        mBaiduModel.connBaiduNews(mStartIndex, mEndIndex)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        failGetNewsList(call, e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        responseGetNewsList(call, response);
                    }
                });
    }

    private void failGetNewsList(Call call, final IOException e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                e.printStackTrace();
                loadNewsDataFromCache();
                toggleCourseDataRefreshing(false);
                showLoadErrorInfo(e.getMessage());
            }
        });
    }

    private void responseGetNewsList(final Call call, final Response response) throws IOException {
        if (!response.isSuccessful()) {
            toggleCourseDataRefreshing(false);
            loadNewsDataFromCache();
            return;
        }
        String json = null;
        try {
            json = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            loadNewsDataFromCache();
        }

        Gson gson = new Gson();
        BaiduNewResult result = gson.fromJson(json, BaiduNewResult.class);
        if (result == null) {
            toggleCourseDataRefreshing(false);
            loadNewsDataFromCache();
            return;
        }
        final BaiduNewResult.DataBean dataBean = result.getData();
        if (dataBean == null) {
            toggleCourseDataRefreshing(false);
            loadNewsDataFromCache();
            return;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mTotalSize = dataBean.getTotal();
                List<BaiduNewResult.DataBean.ListBean> newData = dataBean.getList();
                //保存到缓存
                saveNewsNewData2SharePre(newData);
                //从缓存中取数据
                loadNewsDataFromCache();

                toggleCourseDataRefreshing(false);
            }
        });
    }


    private void showLoadErrorInfo(String msg) {
        mView.showSnackBar((StringUtils.isEmpty(msg) ? "加载失败、请稍后再试" : msg));
    }

    private void saveNewsNewData2SharePre(List<BaiduNewResult.DataBean.ListBean> newData) {
        NewsListCacheUtil.saveBaiduNews(mContext, newData);
        mView.showSnackBar("新闻列表更新成功（百度新闻提供）", Snackbar.LENGTH_LONG);
    }

    private void loadNewsDataFromCache() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                List<BaiduNewResult.DataBean.ListBean> cacheData =  NewsListCacheUtil.getBaiduNewsCacheByList(mContext);
                if (cacheData == null)  return;
                mData.clear();
                mData.addAll(cacheData);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void loadCourseDataFromCache() {
        LinkedHashMap<String, List<FileInfo>> cacheData = mCourseCacheModel.listCoureseDataByMap(mContext);
        if (cacheData == null) return;
        Log.i("怎么没标题", cacheData.toString());
        mParentChildMap.clear();
        mParentChildMap.putAll(cacheData);
        mExpanableLvAdapter.notifyDataSetChanged();
    }

}
